package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.PageResult;
import com.tju.ocean_ecology_website.dto.StatusUpdateDTO;
import com.tju.ocean_ecology_website.dto.VolunteerDTO;
import com.tju.ocean_ecology_website.dto.VolunteerQueryDTO;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.entity.VolunteerInfo;
import com.tju.ocean_ecology_website.entity.VolunteerServiceRecord;
import com.tju.ocean_ecology_website.service.UserService;
import com.tju.ocean_ecology_website.service.VolunteerInfoService;
import com.tju.ocean_ecology_website.service.VolunteerServiceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 志愿者管理控制器
 */
@RestController
@RequestMapping("/api")
public class VolunteerController {

    @Autowired
    private UserService userService;

    @Autowired
    private VolunteerInfoService volunteerInfoService;

    @Autowired
    private VolunteerServiceRecordService volunteerServiceRecordService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 获取志愿者列表
     *
     * @param queryDTO 查询参数
     * @return 志愿者列表
     */
    @GetMapping("/volunteers")
    public ResponseEntity<ApiResponse<PageResult<VolunteerDTO>>> getVolunteerList(VolunteerQueryDTO queryDTO) {
        // 创建用户筛选条件
        User userQuery = new User();
        userQuery.setRole(2); // 志愿者角色
        if (queryDTO.getUsername() != null && !queryDTO.getUsername().isEmpty()) {
            userQuery.setUsername(queryDTO.getUsername());
        }
        if (queryDTO.getStatus() != null) {
            userQuery.setStatus(queryDTO.getStatus());
        }
        if (queryDTO.getName() != null && !queryDTO.getName().isEmpty()) {
            userQuery.setName(queryDTO.getName());
        }

        // 查询用户数据
        PageRequest pageRequest = queryDTO.toPageRequest();
        Page<User> userPage = userService.queryByPage(userQuery, pageRequest);

        // 构建志愿者DTO列表
        List<VolunteerDTO> volunteerDTOs = new ArrayList<>();
        for (User user : userPage.getContent()) {
            // 查询志愿者信息
            VolunteerInfo volunteerInfo = null;
            VolunteerInfo query = new VolunteerInfo();
            query.setUserId(user.getId());
            Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(query, PageRequest.of(0, 1));
            if (!volunteerInfoPage.isEmpty()) {
                volunteerInfo = volunteerInfoPage.getContent().get(0);
            }

            // 如果有真实姓名筛选条件，且不匹配，则跳过
            if (queryDTO.getRealName() != null && !queryDTO.getRealName().isEmpty() &&
                (volunteerInfo == null || !volunteerInfo.getRealName().contains(queryDTO.getRealName()))) {
                continue;
            }

            // 构建DTO
            VolunteerDTO dto = VolunteerDTO.fromUserAndVolunteerInfo(user, volunteerInfo);
            volunteerDTOs.add(dto);
        }

        // 创建分页结果
        Page<VolunteerDTO> dtoPage = new PageImpl<>(volunteerDTOs, pageRequest, userPage.getTotalElements());
        PageResult<VolunteerDTO> pageResult = PageResult.fromPage(dtoPage, queryDTO.getPage());

        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 获取志愿者详情
     *
     * @param id 志愿者ID（用户ID）
     * @return 志愿者详情
     */
    @GetMapping("/volunteers/{id}")
    public ResponseEntity<ApiResponse<VolunteerDTO>> getVolunteerDetail(@PathVariable("id") Long id) {
        // 查询用户信息
        User user = userService.queryById(id);
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "志愿者不存在"));
        }

        // 查询志愿者信息
        VolunteerInfo volunteerInfo = null;
        VolunteerInfo query = new VolunteerInfo();
        query.setUserId(user.getId());
        Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(query, PageRequest.of(0, 1));
        if (!volunteerInfoPage.isEmpty()) {
            volunteerInfo = volunteerInfoPage.getContent().get(0);
        }

        // 构建DTO
        VolunteerDTO dto = VolunteerDTO.fromUserAndVolunteerInfo(user, volunteerInfo);

        return ResponseEntity.ok(ApiResponse.success(dto));
    }

    /**
     * 获取志愿者服务记录
     *
     * @param id 志愿者ID（用户ID）
     * @param page 页码
     * @param pageSize 每页大小
     * @return 服务记录列表
     */
    @GetMapping("/volunteers/{id}/services")
    public ResponseEntity<ApiResponse<PageResult<VolunteerServiceRecord>>> getVolunteerServiceRecords(
            @PathVariable("id") Long id,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        // 查询用户信息
        User user = userService.queryById(id);
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "志愿者不存在"));
        }

        // 查询志愿者信息
        VolunteerInfo volunteerInfo = null;
        VolunteerInfo query = new VolunteerInfo();
        query.setUserId(user.getId());
        Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(query, PageRequest.of(0, 1));
        if (volunteerInfoPage.isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "志愿者信息不存在"));
        }
        volunteerInfo = volunteerInfoPage.getContent().get(0);

        // 查询服务记录
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Page<VolunteerServiceRecord> recordPage = volunteerServiceRecordService.queryByVolunteerId(volunteerInfo.getId(), pageRequest);

        // 创建分页结果
        PageResult<VolunteerServiceRecord> pageResult = PageResult.fromPage(recordPage, page);

        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 添加志愿者
     *
     * @param volunteerDTO 志愿者信息
     * @return 添加结果
     */
    @PostMapping("/volunteers")
    public ResponseEntity<ApiResponse<VolunteerDTO>> addVolunteer(@RequestBody VolunteerDTO volunteerDTO) {
        // 创建用户
        User user = new User();
        user.setUsername("volunteer"+ volunteerDTO.getName());
        // 默认密码为123456
        user.setPassword(passwordEncoder.encode("123456"));
        user.setName(volunteerDTO.getName());
        user.setEmail(volunteerDTO.getEmail());
        user.setPhone(volunteerDTO.getPhone());
        user.setAvatar(volunteerDTO.getAvatar());

        user.setRole(2); // 志愿者角色
        user.setStatus(1); // 默认启用
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        User savedUser = userService.insert(user);

        // 创建志愿者信息
        VolunteerInfo volunteerInfo = new VolunteerInfo();
        volunteerInfo.setUserId(savedUser.getId());
        volunteerInfo.setRealName(volunteerDTO.getName());
        volunteerInfo.setGender(volunteerDTO.getGender());
        volunteerInfo.setBirthDate(volunteerDTO.getBirthDate());
        volunteerInfo.setRegion(volunteerDTO.getRegion());
        volunteerInfo.setSkills(volunteerDTO.getSkills());
        volunteerInfo.setVolunteerHours(0); // 初始服务时长为0
        volunteerInfo.setCreateTime(new Date());
        volunteerInfo.setUpdateTime(new Date());

        VolunteerInfo savedVolunteerInfo = volunteerInfoService.insert(volunteerInfo);

        // 构建返回DTO
        VolunteerDTO resultDTO = VolunteerDTO.fromUserAndVolunteerInfo(savedUser, savedVolunteerInfo);

        return ResponseEntity.ok(ApiResponse.success(resultDTO, "添加志愿者成功"));
    }

    /**
     * 更新志愿者信息
     *
     * @param id 志愿者ID（用户ID）
     * @param volunteerDTO 志愿者信息
     * @return 更新结果
     */
    @PutMapping("/volunteers/{id}")
    public ResponseEntity<ApiResponse<VolunteerDTO>> updateVolunteer(
            @PathVariable("id") Long id,
            @RequestBody VolunteerDTO volunteerDTO) {

        // 查询用户信息
        User user = userService.queryById(id);
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "志愿者不存在"));
        }

        // 更新用户信息
        user.setName(volunteerDTO.getName());
        user.setEmail(volunteerDTO.getEmail());
        user.setPhone(volunteerDTO.getPhone());
        if (volunteerDTO.getAvatar() != null) {
            user.setAvatar(volunteerDTO.getAvatar());
        }
        user.setUpdateTime(new Date());

        User updatedUser = userService.update(user);

        // 查询志愿者信息
        VolunteerInfo volunteerInfo = null;
        VolunteerInfo query = new VolunteerInfo();
        query.setUserId(user.getId());
        Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(query, PageRequest.of(0, 1));
        if (volunteerInfoPage.isEmpty()) {
            // 如果不存在，创建新的志愿者信息
            volunteerInfo = new VolunteerInfo();
            volunteerInfo.setUserId(user.getId());
            volunteerInfo.setCreateTime(new Date());
        } else {
            volunteerInfo = volunteerInfoPage.getContent().get(0);
        }

        // 更新志愿者信息
        volunteerInfo.setRealName(volunteerDTO.getRealName());
        volunteerInfo.setGender(volunteerDTO.getGender());
        volunteerInfo.setBirthDate(volunteerDTO.getBirthDate());
        volunteerInfo.setRegion(volunteerDTO.getRegion());
        volunteerInfo.setSkills(volunteerDTO.getSkills());
        volunteerInfo.setUpdateTime(new Date());

        VolunteerInfo updatedVolunteerInfo;
        if (volunteerInfo.getId() == null) {
            updatedVolunteerInfo = volunteerInfoService.insert(volunteerInfo);
        } else {
            updatedVolunteerInfo = volunteerInfoService.update(volunteerInfo);
        }

        // 构建返回DTO
        VolunteerDTO resultDTO = VolunteerDTO.fromUserAndVolunteerInfo(updatedUser, updatedVolunteerInfo);

        return ResponseEntity.ok(ApiResponse.success(resultDTO, "更新志愿者信息成功"));
    }

    /**
     * 删除志愿者
     *
     * @param id 志愿者ID（用户ID）
     * @return 删除结果
     */
    @DeleteMapping("/volunteers/{id}")
    public ResponseEntity<ApiResponse<Boolean>> deleteVolunteer(@PathVariable("id") Long id) {
        // 查询用户信息
        User user = userService.queryById(id);
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "志愿者不存在"));
        }

        // 查询志愿者信息
        VolunteerInfo volunteerInfo = null;
        VolunteerInfo query = new VolunteerInfo();
        query.setUserId(user.getId());
        Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(query, PageRequest.of(0, 1));
        if (!volunteerInfoPage.isEmpty()) {
            volunteerInfo = volunteerInfoPage.getContent().get(0);
            // 删除志愿者信息
            volunteerInfoService.deleteById(volunteerInfo.getId());
        }

        // 删除用户
        boolean result = userService.deleteById(id);

        return ResponseEntity.ok(ApiResponse.success(result, result ? "删除志愿者成功" : "删除志愿者失败"));
    }

    /**
     * 修改志愿者状态
     *
     * @param id 志愿者ID（用户ID）
     * @param statusUpdateDTO 状态更新DTO
     * @return 更新结果
     */
    @PostMapping("/volunteers/{id}/status")
    public ResponseEntity<ApiResponse<User>> changeVolunteerStatus(
            @PathVariable("id") Long id,
            @Valid @RequestBody StatusUpdateDTO statusUpdateDTO) {

        // 查询用户信息
        User user = userService.queryById(id);
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "志愿者不存在"));
        }

        // 更新状态
        user.setStatus(statusUpdateDTO.getStatus());
        user.setUpdateTime(new Date());

        User updatedUser = userService.update(user);

        return ResponseEntity.ok(ApiResponse.success(updatedUser, "修改志愿者状态成功"));
    }

    /**
     * 重置志愿者密码
     *
     * @param id 志愿者ID（用户ID）
     * @return 重置结果
     */
    @PutMapping("/volunteers/{id}/reset-password")
    public ResponseEntity<ApiResponse<Boolean>> resetVolunteerPassword(@PathVariable("id") Long id) {
        // 查询用户信息
        User user = userService.queryById(id);
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "志愿者不存在"));
        }

        // 重置密码为123456
        user.setPassword(passwordEncoder.encode("123456"));
        user.setUpdateTime(new Date());

        userService.update(user);

        return ResponseEntity.ok(ApiResponse.success(true, "重置密码成功"));
    }
}
